import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'node:fs'
import path from 'node:path'

// 检查证书文件是否存在
const certPath = path.resolve(__dirname, './.cert/cert.pem');
const keyPath = path.resolve(__dirname, './.cert/key.pem');
const httpsOptions = 
  fs.existsSync(certPath) && fs.existsSync(keyPath)
    ? {
        key: fs.readFileSync(keyPath),
        cert: fs.readFileSync(certPath),
      }
    : undefined;

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const isHttps = mode === 'https';
  
  return {
    plugins: [
      vue()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    server: {
      port: 5173,
      host: '0.0.0.0',
      allowedHosts: [
        'localhost',
        '127.0.0.1'
      ],
      cors: true,
      https: isHttps ? httpsOptions : false,
      proxy: {
        '/api': {
          target: 'http://localhost:8081',
          secure: false,
          changeOrigin: true
        },
        '/ws': {
          target: 'ws://localhost:8081',
          ws: true,
          secure: false,
          changeOrigin: true,
          rewrite: (path) => path
        }
      }
    },
  }
})
